<script setup>
import { ref, reactive, toRefs, onMounted, computed, watch } from "vue";
import { cartListSend, selectedSend, deleCartListSend } from "@/api/cart";
const checkAll = ref(false);
const isIndeterminate = ref(false);
// const cities = ["Shanghai", "Beijing", "Guangzhou", "Shenzhen"];
const react = reactive({
  cart: [],
  selectedData: [],
  cities: "",
  time: "",
  loading: "",
});
const { cart, selectedData, cities, time, loading } = toRefs(react);
const initCartList = async () => {
  const data = await cartListSend();
  cart.value = data.result;
  selectedData.value = data.result
    .map((item) => {
      if (item.selected) {
        return item.skuId;
      }
    })
    .filter((res) => res != undefined);
  cities.value = data.result.map((item) => {
    return item.skuId;
  });
  isIndeterminate.value =
    selectedData.value.length > 0 &&
    selectedData.value.length < cities.value.length;
  if (selectedData.value.toString() == cities.value.toString()) {
    checkAll.value = true;
  } else {
    checkAll.value = false;
  }
};

initCartList();

const handleCheckAllChange = async (val) => {
  console.log(val);

  await selectedSend({ selected: val });
  await initCartList();

  selectedData.value = val ? cities.value : [];
  isIndeterminate.value = false;
};
const handleCheckedCitiesChange = async (value) => {
  // console.log(value);
  // 购物车单选 方法一：
  const arr = cities.value
    .map((item) => {
      let bool = value.some((tag) => {
        return item == tag;
      });

      if (!bool) {
        return item;
      }
    })
    .filter((res) => res != undefined);

  console.log(arr);
  if (time) {
    clearTimeout(time.value);
    time.value = "";
  }
  time.value = setTimeout(async () => {
    loading.value = ElLoading.service({
      lock: true,
      text: "Loading",
    });
    await Promise.all([
      selectedSend({ selected: true, ids: value }),
      selectedSend({ selected: false, ids: arr }),
    ]);
    loading.value.close();
    await initCartList();
  }, 1000);

  const checkedCount = value.length;
  checkAll.value = checkedCount === cities.value.length;
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < cities.value.length;
};
// const checkBoxClick = async (selected, id) => {
//   console.log('xx');
//   // 购物车单选 方法二：
//   // await selectedSend({ selected: !selected, ids: [id] });
//   // await initCartList();
// };
const value = ref("Option1");

const options = [
  {
    value: "Option1",
    label: "Option1",
  },
  {
    value: "Option2",
    label: "Option2",
  },
];

onMounted(() => {});

const addNum = (i) => {
  if (cart.value[i].stock > 99) {
    if (cart.value[i].count + 1 <= 99) {
      cart.value[i].count += 1;
    } else {
      ElMessage({
        message: "最多加入99件商品",
        type: "warning",
      });
    }
  } else {
    if (cart.value[i].count + 1 <= cart.value[i].stock) {
      cart.value[i].count += 1;
    } else {
      ElMessage({
        message: "库存不足",
        type: "warning",
      });
    }
  }
};
const romeNum = (i) => {
  if (cart.value[i].count - 1 > 0) {
    cart.value[i].count -= 1;
  }
};

const settlement = computed(() => {
  const and = cart.value
    .map((item) => {
      let subtotal = item.count * Number(item.price);
      return item.selected ? subtotal : "";
    })
    .filter((res) => res);
  console.log(and);
  return and.reduce((total, item) => {
    return total + item;
  }, 0);
});

const deleCart = async (id) => {
  const data = await deleCartListSend({ ids: [id] });
  console.log(data);
};
</script>

<template>
  <div class="shopping-cart">
    <div class="app-content-center">
      <div style="padding: 15px 0; font-size:16px">我的购物车</div>
      <div v-if="cart.length" class="shopping-q">
        <div>购物车可领优惠券</div>
        <div>领取</div>
      </div>

      <div class="shopping-box-list" v-if="cart.length">
        <table>
          <tr>
            <th style="width: 10%; text-align: left; padding-left: 3%">
              <el-checkbox
                v-model="checkAll"
                :indeterminate="isIndeterminate"
                @change="handleCheckAllChange"
                >全选</el-checkbox
              >
            </th>
            <th style="width: 30%">商品信息</th>
            <th style="width: 20%">单价</th>
            <th style="width: 20%">数量</th>
            <th style="width: 10%">小计</th>
            <th style="width: 10%">操作</th>
          </tr>

          <el-checkbox-group
            v-model="selectedData"
            @change="handleCheckedCitiesChange"
          >
            <tbody>
              <tr v-for="(item, index) in cart" :key="item.id">
                <td style="width: 10%; text-align: left; padding-left: 3%">
                  <div>
                    <el-checkbox :label="item.skuId">{{ "" }}</el-checkbox>
                  </div>
                </td>
                <td style="width: 30%">
                  <div class="shopping-good-info">
                    <img :src="item.picture" alt="" />
                    <div style="width: 70%">
                      <p>{{ item.name }}</p>
                      <p>
                        <!-- <el-select v-model="value" size="small">
                          <el-option
                            v-for="item in options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                          />
                        </el-select> -->
                        {{ item.attrsText }}
                      </p>
                      <p v-if="item.stock > 20">库存 {{ item.stock }}</p>
                      <p v-else style="color: red">
                        库存紧张，不足{{ item.stock }}
                      </p>
                    </div>
                  </div>
                </td>
                <td style="width: 20%">
                  <p>¥{{ item.nowPrice }}</p>
                  <p v-if="item.price - item.nowPrice">
                    比加入时降价 ¥{{ item.price - item.nowPrice }}
                  </p>
                </td>
                <td style="width: 20%">
                  <div class="shopping-num">
                    <div @click="romeNum(index)">-</div>
                    <p>{{ item.count }}</p>
                    <div @click="addNum(index)">+</div>
                  </div>
                </td>
                <td style="width: 10%; color: red">
                  ¥{{ item.count * Number(item.price) }}
                </td>
                <td style="width: 10%" class="operation">
                  <p>移入收藏夹</p>
                  <p>找相似</p>
                  <p @click="deleCart(item.skuId)">删除</p>
                </td>
              </tr>
            </tbody>
          </el-checkbox-group>
        </table>
        <div class="shopping-box-settlement">
          <div>
            <el-checkbox
              v-model="checkAll"
              :indeterminate="isIndeterminate"
              @change="handleCheckAllChange"
              >全选</el-checkbox
            >

            <span>删除商品</span>
            <span>移入收藏夹</span>
            <span>清空失效商品</span>
          </div>

          <div>
            <span
              >共 {{ cities.length }} 件商品，已选择
              {{ selectedData.length }} 件</span
            >
            <span> 商品合计：¥{{ settlement }} 活动优惠：-¥0.00 </span>
            <span
              >应付总额：
              <span style="font-size: 17px; color: #f04844"
                >¥ {{ settlement }}</span
              ></span
            >
            <div class="settlement-btn">下单结算</div>
          </div>
        </div>
      </div>

      <div class="null-cart">
        <i class="iconfont icon-gouwuche"> 
          
          <div>购物车内暂时没有商品</div>
        </i>
        <div class="null-cart-btn">继续逛逛</div>
      </div>
    </div>
  </div>
</template>

<style lang="scss">
.shopping-cart {
  .shopping-q{
    display: flex;
    justify-content: space-between;
    background-color: #fff;
    margin-bottom: 10px;

    div{
      padding: 10px 20px;
      border: 1px solid #aaa;
    }
  }

  .shopping-box-list {
    table {
      display: block;
      width: 100%;

      tr {
        display: block;
        width: 100%;
        text-align: center;
        background-color: #f9f9f9;

        .el-checkbox__label {
          font-size: 15px;
          font-weight: 1000;
        }
        th {
          box-sizing: border-box;
          display: inline-block;
          font-size: 15px;
        }
      }

      tbody {
        display: block;
        tr {
          display: block;
          width: 100%;
          background-color: #fff;
          padding: 20px 0;
          & ~ tr {
            border-top: 1px solid #ddd;
          }

          td {
            display: inline-block;
            box-sizing: border-box;
            p {
              padding: 5px 0;
            }

            .shopping-num {
              display: flex;
              justify-content: center;

              div {
                padding: 8px 15px;
                border: 1px solid #eee;
                cursor: pointer;
                background-color: #f8f8f8;
              }

              p {
                padding: 8px 0;
                width: 60px;
                border-top: 1px solid #eee;
                border-bottom: 1px solid #eee;
              }
            }
          }

          .shopping-good-info {
            width: 100%;
            display: flex;
            align-items: center;
            img {
              width: 30%;
              height: 3 0%;
            }

            div {
              text-align: left;
              p {
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                padding: 5px 5px 5px 10px;
              }
            }
          }
        }
      }
    }

    .shopping-box-settlement {
      display: flex;
      margin: 20px 0;
      padding: 0 0 0 35px;
      background-color: #fff;
      align-items: center;
      justify-content: space-between;
      font-size: 15px;
      .el-checkbox {
        .el-checkbox__inner {
          padding: 0;
        }
        .el-checkbox__label {
          font-size: 15px;
          padding: 0 0 0 5px;
        }

        span {
          padding: 0;
        }
      }
      span {
        padding: 0 15px;
      }
      div {
        display: flex;
        align-items: center;
      }

      .settlement-btn {
        height: 60px;
        padding: 0 20px;
        background-color: #f04844;
        color: #fff;
      }
    }
  }

  .null-cart {
    background-color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    text-align: center;
    padding: 30px 0 100px 0;
    .iconfont {
      font-size: 150px;
      position: relative;
      color: #cccccc;
      width: 100%;

      div {
        position: absolute;
        font-size: 25px;
        left: 0;
        width: 100%;
        bottom: 0;
      }
    }

    .null-cart-btn {
      padding: 10px 20px;
      background-color: #f5f5f5;
      color: #aaa;
      margin-top: 10px;
      font-size: 15px;
    }
  }
}

.el-checkbox-group {
  font-size: larger;
  line-height: 100%;
}
</style>
